package com.github.natholdallas.common

import cn.dev33.satoken.stp.StpUtil
import com.github.natholdallas.context
import com.github.natholdallas.database.LogTable
import com.github.natholdallas.database.Logs
import com.github.natholdallas.database.Users
import com.github.natholdallas.declaration.InvalidException
import org.springframework.validation.FieldError
import org.springframework.validation.ObjectError
import java.text.SimpleDateFormat
import java.util.*
import kotlin.reflect.KClass

inline val USER get() = getBean(Users::class).byId(StpUtil.getLoginIdAsLong())
inline val USERNAME get() = USER.username
inline val LOGINID get() = StpUtil.getLoginIdAsLong()
inline val CURTIME get() = System.currentTimeMillis()
inline val UNIQUE_UUID: UUID get() = UUID(UUID.randomUUID().mostSignificantBits, CURTIME)
inline val RANDOM_UUID: UUID get() = UUID.randomUUID()

fun isTrue(expression: Boolean, vararg msgs: String) {
    if (expression) return
    throw InvalidException(*msgs)
}

fun isFalse(expression: Boolean, vararg msgs: String) {
    if (!expression) return
    throw InvalidException(*msgs)
}

fun <T : Any> getBean(clazz: KClass<T>): T {
    return context.getBean(clazz.java)
}

fun resolveInvalid(v: ObjectError): String =
    if (v is FieldError) "${v.field} : ${v.defaultMessage}"
    else "${v.objectName} : ${v.defaultMessage}"


fun saveLog(msg: String) {
    val datetime = SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(Date())
    getBean(Logs::class).save(LogTable(msg = "[$datetime] $msg"))
}
